package com.whfc.iot.mach.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @Description: 设备升级乐观锁
 * @author: xugcheng
 * @version: 1.0
 * @date: 2021-02-05 17:38
 */
@Component
public class MachUpgradeLockDao {

    public static final String key = "device-upgrade-lock";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 加锁
     *
     * @param deviceId
     * @param lockValue
     */
    public void lock(Integer deviceId, long lockValue) {
        redisTemplate.opsForHash().put(key, String.valueOf(deviceId), String.valueOf(lockValue));
    }

    /**
     * 获取锁
     *
     * @param deviceId
     * @return
     */
    public long getLock(Integer deviceId) {
        Object val = redisTemplate.opsForHash().get(key, String.valueOf(deviceId));
        return val != null ? Long.parseLong(String.valueOf(val)) : 0;
    }

    /**
     * 解锁
     *
     * @param deviceId
     */
    public void unlock(Integer deviceId) {
        redisTemplate.opsForHash().delete(key, String.valueOf(deviceId));
    }
}
